import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:flutter_test1/extension/num_extension.dart';
import 'package:flutter_test1/extension/string_extension.dart';
import 'package:flutter_test1/helper/dialog/base_style_widget.dart';
import 'package:flutter_test1/helper/dialog/common_style_widget.dart';
import 'package:get/get.dart';

class DialogHelper {
  ///弹窗显示时是否使用动画，统一控制变量
  static const bool _isUseAnimation = false;

  ///封装弹窗显示统一显示出口
  /// 自定义弹窗
  /// [builder]：自定义 dialog
  /// [controller]：可使用该控制器来刷新自定义的dialog的布局
  /// [alignment]：控制弹窗的位置
  /// [clickMaskDismiss]：true（点击遮罩后，将关闭dialog），false（不关闭）
  /// [animationType]：具体可参照[SmartAnimationType]注释
  /// [usePenetrate]：true（点击事件将穿透遮罩），false（不穿透）
  /// [useAnimation]：true（使用动画），false（不使用）
  /// [animationTime]：动画持续时间
  /// [maskColor]：遮罩颜色，如果给[maskWidget]设置了值，该参数将会失效
  /// [maskWidget]：可高度定制遮罩
  /// [debounce]：防抖功能
  /// [tag]：如果你给dialog设置了tag, 你可以针对性的关闭它
  /// [backDismiss]：true（返回事件将关闭dialog，但是不会关闭页面），
  /// false（返回事件不会关闭loading，也不会关闭页面），你仍然可以使用dismiss方法来关闭loading
  /// [keepSingle]：默认（false），true（多次调用[show]并不会生成多个dialog，仅仅保持一个dialog），
  /// false（多次调用[show]会生成多个dialog）
  /// [permanent]：默认（false），true（将该dialog设置为永久化dialog）,false(不设置);
  /// 框架内部各种兜底操作(返回事件,路由)无法关闭永久化dialog, 需要关闭此类dialog可使用: dismiss(force: true)
  /// [useSystem]：默认（false），true（使用系统dialog，[usePenetrate]功能失效; [tag], [keepSingle], [permanent]和[bindPage]禁止使用），
  /// false（使用SmartDialog），使用该参数可使SmartDialog, 与路由页面以及flutter自带dialog合理交互
  /// [bindPage]：将该dialog与当前页面绑定，绑定页面不在路由栈顶，dialog自动隐藏，绑定页面置于路由栈顶，dialog自动显示;
  /// 绑定页面被关闭,被绑定在该页面上的dialog也将被移除
  static Future<T?> show<T>({
    required Widget widget,
    SmartDialogController? controller,
    Alignment? alignment,
    SmartAnimationType? animationType,
    bool? clickBgDismiss,
    bool? isLoadingTemp,
    bool? isPenetrate,
    bool? isUseAnimation,
    Duration? animationTime,
    Color? maskColor,
    Widget? maskWidget,
    bool? debounce,
    VoidCallback? onDismiss,
    VoidCallback? onMaskTap,
    String? tag,
    bool? backDismiss,
    bool? keepSingle,
    bool? useSystem,
    bool? permanent,
    bool bindPage = false,
  }) async {
    return SmartDialog.show(
        builder: (context) {
          return widget;
        },
        animationType: animationType,
        controller: controller,
        alignment: alignment,
        clickMaskDismiss: clickBgDismiss,
        usePenetrate: isPenetrate,
        useAnimation: isUseAnimation ?? _isUseAnimation,
        animationTime: animationTime,
        maskColor: maskColor,
        maskWidget: maskWidget,
        debounce: debounce,
        permanent: permanent,
        onDismiss: () {
          onDismiss?.call();
        },
        onMask: onMaskTap,
        tag: tag,
        backDismiss: backDismiss,
        keepSingle: keepSingle,
        bindPage: bindPage,
        useSystem: useSystem);
  }

  static Future<void> dismiss<T>({
    SmartStatus status = SmartStatus.smart,
    String? tag,
    T? result,
    bool force = false,
  }) async {
    return SmartDialog.dismiss(
      status: status,
      tag: tag,
      result: result,
      force: force,
    );
  }

  ///通用弹窗封装
  static Future<void> showConfirmDialog(
      {String title = "提示",
      String? subTitle, //子标题
      String? content, //内容
      Widget? contentWidget, //内容部分,优先使用`content`字符串来显示
      Function()? onCancelTap,
      Function()? onOkTap,
      Function()? onMaskTap,
      Function()? onCloseTap,
      String? cancelText,
      Color? cancelColor,
      String? okText,
      Color? okColor,
      Widget? okWidget, //内容部分,优先使用`okText`字符串来显示
      String? tag,
      bool keepSingle = false,
      bool clickBgDismiss = false,
      bool isSingleBtn = false,
      bool backDismiss = false,
      bool showCloseBtn = true,
      String? imagePath,
      TextAlign titleTextAlign = TextAlign.center,
      TextAlign contentTextAlign = TextAlign.center,
      bool bindPage = false,
      bool isTapBtnDismiss = true,
      BaseStyleWidget? baseStyleWidget,
      Function()? onDismiss}) {
    var commonWidget = baseStyleWidget ??
        CommonStyleWidget(
          title: title,
          subTitle: subTitle,
          content: content,
          contentWidget: contentWidget,
          onCancelTap: onCancelTap,
          onOkTap: onOkTap,
          onCloseTap: onCloseTap,
          cancelText: cancelText ?? '取消',
          cancelColor: cancelColor,
          okText: okText ?? '确认',
          okWidget: okWidget,
          okColor: okColor,
          tag: tag,
          isSingleBtn: isSingleBtn,
          showCloseBtn: showCloseBtn,
          titleTextAlign: titleTextAlign,
          contentTextAlign: contentTextAlign,
          isTapBtnDismiss: isTapBtnDismiss,
        );
    return show(
      widget: commonWidget,
      maskColor: const Color(0x7f000000),
      alignment: Alignment.center,
      backDismiss: backDismiss,
      bindPage: bindPage,
      onMaskTap: onMaskTap,
      tag: keepSingle ? null : tag,
      isPenetrate: false,
      keepSingle: keepSingle,
      clickBgDismiss: clickBgDismiss,
      isUseAnimation: true,
      animationType: SmartAnimationType.centerScale_otherSlide,
    );
  }

  ///统一loading弹窗显示
  static void showLoading({
    String? msg,
    SmartDialogController? controller,
    Alignment? alignment,
    bool? clickMaskDismiss,
    SmartAnimationType? animationType,
    List<SmartNonAnimationType>? nonAnimationTypes,
    Widget Function(AnimationController, Widget, AnimationParam)?
        animationBuilder,
    bool? usePenetrate,
    bool? useAnimation,
    Duration? animationTime,
    Color? maskColor,
    Widget? maskWidget,
    void Function()? onDismiss,
    void Function()? onMask,
    Duration? displayTime,
    bool? backDismiss,
    Widget Function(BuildContext)? builder,
  }) {
    SmartDialog.showLoading(
      msg: msg ?? '加载中',
      controller: controller,
      alignment: alignment,
      clickMaskDismiss: clickMaskDismiss,
      animationType: animationType,
      nonAnimationTypes: nonAnimationTypes,
      animationBuilder: animationBuilder,
      usePenetrate: usePenetrate,
      useAnimation: useAnimation,
      animationTime: animationTime,
      maskColor: maskColor,
      maskWidget: maskWidget,
      onDismiss: onDismiss,
      onMask: onMask,
      displayTime: displayTime,
      backDismiss: backDismiss,
      builder: builder,
    );
  }

  static Future<void> hideLoading() async {
    return await SmartDialog.dismiss(status: SmartStatus.loading);
  }

  static void hideCustomDialog() {
    SmartDialog.dismiss(status: SmartStatus.custom);
  }

  ///弹出通用自定义弹窗，不含默认按纽
  static void showCenterDialog(
    Widget widget, {
    bool clickBgDismissTemp = true,
    bool backDismiss = true,
    bool debounceTemp = true,
    bool permanent = false,
    bool keepSingle = false,
    bool isNeedCommonStyle = true,
    double width = 280,
    String? tag,
    bool bindPage = true,
    VoidCallback? onDismiss,
    VoidCallback? onMaskTap,
    Color? backgroundColor,
  }) {
    var custom = !isNeedCommonStyle
        ? widget
        : Container(
            width: width,
            decoration: BoxDecoration(
              color: backgroundColor ?? Colors.white,
              borderRadius: BorderRadius.circular(8.r),
            ),
            child: widget,
          );
    show(
      widget: custom,
      maskColor: const Color(0x99000000),
      alignment: Alignment.center,
      backDismiss: backDismiss,
      onMaskTap: onMaskTap,
      isUseAnimation: true,
      onDismiss: onDismiss,
      animationType: SmartAnimationType.centerScale_otherSlide,
      bindPage: bindPage,
      tag: keepSingle ? null : tag,
      isPenetrate: false,
      keepSingle: keepSingle,
      clickBgDismiss: clickBgDismissTemp,
    );
  }

  static void showSheetDlg<T>(List<T> list,
      {required void Function(T item, int index) onTap,
      String? tag,
      bool isTapDismiss = true,
      String Function(T item)? onShowParse}) {
    Widget buildSheetItem(int index) {
      var text = index == -1 ? '取消' : onShowParse?.call(list.elementAt(index));
      return GestureDetector(
        onTap: () {
          if (index >= 0) {
            onTap.call(list.elementAt(index), index);
          }
          if (isTapDismiss || index == -1) {
            DialogHelper.dismiss(tag: tag ?? "showSheetDlg");
          }
        },
        child: Container(
          alignment: Alignment.center,
          padding: const EdgeInsets.symmetric(vertical: 15),
          child: (text ?? list.elementAt(index).toString())
              .extText(color: const Color(0xFF363538), fontSize: 15),
        ),
      );
    }

    showBottomDlg(
        tag: tag ?? "showSheetDlg",
        Container(
          padding: const EdgeInsets.only(left: 16, right: 16, bottom: 10),
          child: Column(mainAxisSize: MainAxisSize.min, children: [
            Container(
              width: Get.width,
              // decoration: AppStyle.boxCornerAllColor(Colors.white, 12),
              decoration: BoxDecoration(
                borderRadius: BorderRadius.all(Radius.circular(12)),
                color: Colors.white
              ),
              child: ListView.separated(
                padding: EdgeInsets.zero,
                shrinkWrap: true,
                itemBuilder: (context, index) {
                  return buildSheetItem(index);
                },
                itemCount: list.length,
                separatorBuilder: (BuildContext context, int index) {
                  return const Padding(
                    padding: EdgeInsets.symmetric(horizontal: 16),
                    child: Divider(
                      height: 0.5,
                      color: Color(0xFFF1F1F1),
                    ),
                  );
                },
              ),
            ),
            8.h.extHeightBox,
            Container(
              alignment: Alignment.center,
              width: Get.width,
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(12),
              ),
              child: buildSheetItem(-1),
            ),
          ]),
        ));
  }

  static void showAttachSheetDlg<T>(List<T> list, BuildContext targetContext,
      {required void Function(T item, int index) onTap,
      String? tag,
      bool isTapDismiss = true,
      String Function(T item)? onShowParse}) {
    Widget buildSheetItem(int index) {
      var text = index == -1 ? '取消' : onShowParse?.call(list.elementAt(index));
      return GestureDetector(
        onTap: () {
          if (index >= 0) {
            onTap.call(list.elementAt(index), index);
          }
          if (isTapDismiss || index == -1) {
            DialogHelper.dismiss(tag: tag ?? "showAttachSheetDlg");
          }
        },
        child: Container(
          alignment: Alignment.center,
          padding: const EdgeInsets.symmetric(vertical: 15),
          child: (text ?? list.elementAt(index).toString())
              .extText(color: const Color(0xFF363538), fontSize: 15),
        ),
      );
    }

    SmartDialog.showAttach(
      tag: "showAttachSheetDlg",
      targetContext: targetContext,
      maskColor: Colors.transparent,
      alignment: Alignment.bottomLeft,
      builder: (context) {
        return Container(
          width: 84,
          color: Colors.white,
          decoration: BoxDecoration(
            border: Border.all(color: const Color(0xFFF1F1F1)),
            borderRadius: BorderRadius.all(Radius.circular(4))
          ),
          child: ListView.separated(
            padding: EdgeInsets.zero,
            shrinkWrap: true,
            itemBuilder: (context, index) {
              return buildSheetItem(index);
            },
            itemCount: list.length,
            separatorBuilder: (BuildContext context, int index) {
              return Padding(
                padding: const EdgeInsets.symmetric(horizontal: 6),
                child: Divider(),
              );
            },
          )
        );
      },
    );
  }

  static void showBottomDlg(Widget widget,
      {String? tag,
      bool? clickBgDismiss,
      void Function()? onDismiss,
      Widget? maskWidget,
      VoidCallback? onMaskTap}) {
    show(
        onDismiss: onDismiss,
        tag: tag,
        widget: widget,
        clickBgDismiss: clickBgDismiss,
        isUseAnimation: true,
        onMaskTap: onMaskTap,
        maskWidget: maskWidget,
        alignment: Alignment.bottomCenter,
        animationType: SmartAnimationType.centerScale_otherSlide);
  }

  static void showCommonBottomDlg(Widget widget,
      {String? tag,
      String? title,
      double? height,
      bool isShowClose = false,
      bool keepSingle = true}) {
    var container = Container(
      height: height,
      width: Get.width,
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(12),
      ),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          Stack(
            alignment: Alignment.center,
            children: [

              if (!title.isNullOrEmpty())
                Container(
                  margin: EdgeInsets.only(top: 18),
                  child: title!
                      .extText(fontSize: 17, color: const Color(0xFF363538)),
                ),
              if (isShowClose)
                GestureDetector(
                  onTap: () => DialogHelper.dismiss(tag: tag),
                  child: Container(
                    width: 22,
                    height: 22,
                    child: Icon(Icons.close, size: 20,),
                  ),
                )
            ],
          ),
          Expanded(child: widget),
        ],
      ),
    );
    show(
        tag: tag,
        widget: container,
        keepSingle: keepSingle,
        isUseAnimation: true,
        alignment: Alignment.bottomCenter,
        animationType: SmartAnimationType.centerScale_otherSlide);
  }

  static void showRightDlg(
    Widget widget, {
    double? width,
  }) {
    var custom = Container(
      width: width,
      decoration: BoxDecoration(
        color: const Color(0xffffffff),
        borderRadius: BorderRadius.circular(8),
      ),
      child: widget,
    );
    show(
        widget: custom,
        isUseAnimation: true,
        alignment: Alignment.centerRight,
        animationType: SmartAnimationType.centerScale_otherSlide);
  }

  // static void showPickerImageDlg(
  //     Function(String pathOrUrl, PickMediaType mediaType)? onPick,
  //     {bool isAutoUpload = false,
  //     bool pickVideo = false}) {
  //   var picker = ImagePickerSheet(
  //       pickVideo: pickVideo,
  //       onPick: (path, type) async {
  //         if (!isAutoUpload) {
  //           onPick?.call(path, type);
  //           DialogHelper.dismiss(tag: "pickPhotoDlg");
  //           return;
  //         }
  //         String imgPath = path;
  //         DialogHelper.showLoading();
  //         var url = await UserApi.upload(filePath: imgPath);
  //         DialogHelper.hideLoading();
  //         DialogHelper.dismiss(tag: "pickPhotoDlg");
  //         onPick?.call(url, PickMediaType.image);
  //       }).extContainer(color: Colors.white, borderRadius: 12.extBorderRadius);
  //   DialogHelper.showBottomDlg(picker, tag: "pickPhotoDlg");
  // }

}
